package com.spring.sunflower.conversation

import android.media.MediaPlayer
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.spring.sunflower.R
import com.spring.sunflower.base.BaseFragment
import com.spring.sunflower.common.FileUploadCallback
import com.spring.sunflower.constant.Constant
import com.spring.sunflower.dialog.OnPermissionIntroClickListener
import com.spring.sunflower.event.VoiceSendSuccessEvent
import com.spring.sunflower.util.AliUploadUtils
import com.spring.sunflower.util.AudioUtils
import com.spring.sunflower.util.AudioUtils.PlayCallBack
import com.spring.sunflower.widget.ProgressView
import org.greenrobot.eventbus.EventBus
import java.lang.StringBuilder
import java.util.*

/**
 * Created by Kevin on 2021/7/31<br/>
 *
 * Describe:<br/>
 */
class VoiceFragment : BaseFragment<VoicePresenter>(), ConversationContract.VoiceView,
    View.OnClickListener {
    private var tvVoicePlay: TextView? = null
    private var tvVoiceRerecord: TextView? = null
    private var tvVoiceSubmit: TextView? = null
    private var tvVoiceTip: TextView? = null
    private var ivVoiceRerecord: ImageView? = null
    private var ivVoicePlay: android.widget.ImageView? = null
    private var ivVoiceSubmit: android.widget.ImageView? = null
    private var isRecording = false //录音中
    private var isRecordFinish = false //录音结束
    private var isRecordPlay = false //试听过程
    private var isRecordPlayFinish = false //试听结束

    private var audioUtils: AudioUtils? = null
    private var mRecorderTimer: Timer? = null
    private var mRecorderTime = 0
    private var audioLocalPath: String? = null
    private var keyID: String = ""
    private var keySecret: String = ""
    private var securityToken: String = ""
    private var audioNetPath: String? = null
    private var aliUploadUtils: AliUploadUtils? = null
    private var progress: ProgressView? = null
    override fun setLayoutResId(): Int = R.layout.fragment_voice

    override fun initView() {
        keyID = getField(Constant.STS_KEY_ID, "")
        keySecret = getField(Constant.STS_KEY_SECRET, "")
        securityToken = getField(Constant.STS_SECURITY_TOKEN, "")
        aliUploadUtils = AliUploadUtils.getInstance(keyID, keySecret, securityToken)
        tvVoicePlay = mView.findViewById<TextView>(R.id.tv_voice_play)
        tvVoiceRerecord = mView.findViewById<TextView>(R.id.tv_voice_rerecord)
        tvVoiceSubmit = mView.findViewById<TextView>(R.id.tv_voice_submit)
        tvVoiceTip = mView.findViewById<TextView>(R.id.tvVoiceTip)
        ivVoiceRerecord = mView.findViewById<ImageView>(R.id.iv_voice_rerecord)
        ivVoicePlay = mView.findViewById<ImageView>(R.id.iv_voice_record)
        ivVoiceSubmit = mView.findViewById<ImageView>(R.id.iv_voice_submit)
        progress = mView.findViewById(R.id.pvProgress)
        tvVoicePlay!!.text = "点击录制"
        ivVoicePlay!!.setImageResource(R.drawable.ic_voice_record)
        hideOtherButton()
        ivVoicePlay!!.setOnClickListener(this)
        ivVoiceRerecord!!.setOnClickListener(this)
        ivVoiceSubmit!!.setOnClickListener(this)
        audioUtils = AudioUtils.getInstance()
        progress!!.visibility = View.GONE
    }

    override fun initData() {
    }

    override fun initListener() {
    }

    override fun loadData() {
    }

    override fun setPresenter(): VoicePresenter = VoicePresenter(this)
    private fun hideOtherButton() {
        ivVoiceRerecord!!.visibility = View.INVISIBLE
        ivVoiceSubmit!!.visibility = View.INVISIBLE
        tvVoiceRerecord!!.visibility = View.INVISIBLE
        tvVoiceSubmit!!.visibility = View.INVISIBLE
    }

    private fun showOtherButton() {
        ivVoiceRerecord!!.visibility = View.VISIBLE
        ivVoiceSubmit!!.visibility = View.VISIBLE
        tvVoiceRerecord!!.visibility = View.VISIBLE
        tvVoiceSubmit!!.visibility = View.VISIBLE
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.iv_voice_record -> if (!isRecording && !isRecordFinish && !isRecordPlay && !isRecordPlayFinish) {
                if (XXPermissions.isGranted(mActivity,Permission.RECORD_AUDIO)) {
                    //开始录音
                    startRecord()
                } else {
                    showPermissionIntroDialog(
                        getString(R.string.permission_audio_title),
                        getString(R.string.permission_audio_desc),
                        object : OnPermissionIntroClickListener {
                            override fun onClickOK() {
                                XXPermissions.with(mActivity)
                                    .permission(Permission.RECORD_AUDIO)
                                    .request(object : OnPermissionCallback {
                                        override fun onGranted(
                                            permissions: MutableList<String>?,
                                            all: Boolean
                                        ) {
                                            mGratedRecordPermission = true
                                            startRecord()
                                        }

                                        override fun onDenied(
                                            permissions: MutableList<String>?,
                                            never: Boolean
                                        ) {
                                            showPermissionIntroDialog(
                                                getString(R.string.permission_denied_title),
                                                "无法进行录音",
                                                null
                                            )
                                        }
                                    })
                            }

                            override fun onClickCancel() {
                                showPermissionIntroDialog(
                                    getString(R.string.permission_denied_title),
                                    "无法进行录音",
                                    null
                                )
                            }

                        })
                }
            } else if (isRecording) {
                stopRecorder()
            } else if (isRecordFinish && !isRecordPlay) {
                startPlay()
            } else if (isRecordPlay) {
                stopPlay()
            }
            R.id.iv_voice_rerecord -> {
                isRecordPlayFinish = false
                startRecord()
            }
            R.id.iv_voice_submit -> {
                if (isFastClick) return
                aliUploadUtils!!.upLoadFile(
                    audioLocalPath,
                    object : FileUploadCallback<Any?, Any?> {
                        override fun onFailure(str: String) {}
                        override fun onSuccess(
                            paramRequestString: Any?,
                            filePath: String
                        ) {
                            val map: MutableMap<String, String> = HashMap()
//                            map["voiceSignatureDuration"] = mRecorderTime.toString() + ""
//                            map["voiceSignature"] = filePath
//                            mPresenter.updateUserInfo(map)
                            var event = VoiceSendSuccessEvent()
                            event.duration = mRecorderTime.toString()
                            event.audioUrl = filePath
                            EventBus.getDefault().post(event)
                            hideOtherButton()
                            tvVoicePlay!!.text = "点击录制"
                            ivVoicePlay!!.setImageResource(R.drawable.ic_voice_record)
                            isRecording = false //录音中
                            isRecordFinish = false //录音结束
                            isRecordPlay = false //试听过程
                            isRecordPlayFinish = false //试听结束
                            audioLocalPath = ""
                        }

                        override fun onProgress(
                            request: PutObjectRequest,
                            currentSize: Long,
                            totalSize: Long
                        ) {
                        }

                    })
            }
        }
    }

    override fun onPause() {
        super.onPause()
        printD("VoiceFragment onPause")
    }

    override fun onStop() {
        super.onStop()
        printD("VoiceFragment onStop")
    }

    private fun startRecord() {
        isRecording = true
        tvVoicePlay!!.text = "录制中..."
        ivVoicePlay!!.setImageResource(R.drawable.ic_voice_recording)
        val stringBuilder = StringBuilder()
        stringBuilder.append(mActivity.getCacheDir().getAbsolutePath())
        stringBuilder.append("/")
        stringBuilder.append(System.currentTimeMillis())
        stringBuilder.append(".m4a")
        audioLocalPath = stringBuilder.toString()
        audioUtils!!.starRecordM4A(audioLocalPath)
        startTimer()
        hideOtherButton()
    }

    private fun startTimer() {
        progress!!.visibility = View.VISIBLE
        mRecorderTime = 0
        mRecorderTimer = Timer()
        mRecorderTimer!!.schedule(object : TimerTask() {
            override fun run() {
                mActivity.runOnUiThread(Runnable {
                    tvVoiceTip?.setText((++mRecorderTime).toString() + "''")
                    printD("mRecorderTime=$mRecorderTime")
                    progress!!.setProgress(mRecorderTime.toFloat()/60*100)
                    if (mRecorderTime >= 60) {
                        stopRecorder()
                    }
                })
            }
        }, 1000, 1000)
    }

    private fun stopRecorder() {
        isRecordFinish = true
        isRecording = false
        audioUtils!!.cancelRecord()
        tvVoicePlay!!.text = "试听"
        ivVoicePlay!!.setImageResource(R.drawable.ic_voice_play)
        showOtherButton()
        tvVoiceTip!!.visibility = View.INVISIBLE
        cancelTimer()
        progress!!.visibility = View.GONE
    }

    private fun cancelTimer() {
        if (mRecorderTimer != null) {
            mRecorderTimer!!.cancel()
            mRecorderTimer = null
        }
    }

    private fun startPlay() {
        isRecordPlay = true
        isRecording = false
        tvVoicePlay!!.text = "暂停"
        ivVoicePlay!!.setImageResource(R.drawable.ic_voice_pause)
        hideOtherButton()
        if (TextUtils.isEmpty(audioLocalPath)) {
            showToast("音频路径有误:(")
            return
        }
        audioUtils!!.play(audioLocalPath, object : PlayCallBack {
            override fun onCompletion(param1MediaPlayer: MediaPlayer) {
                tvVoicePlay!!.text = "试听"
                isRecordPlay = false
                isRecordPlayFinish = true
                ivVoicePlay!!.setImageResource(R.drawable.ic_voice_play)
                showOtherButton()
            }

            override fun onPrepared(param1MediaPlayer: MediaPlayer) {}
        })
    }

    private fun stopPlay() {
        isRecordPlay = false
        tvVoicePlay!!.text = "试听"
        ivVoicePlay!!.setImageResource(R.drawable.ic_voice_play)
        audioUtils!!.stopPlay()
        isRecordPlayFinish = true
        showOtherButton()
    }
}